package com.yh.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yh.common.exception.NoStockException;
import com.yh.common.to.mq.OrderTo;
import com.yh.common.utils.R;
import com.yh.common.vo.MemberRespVo;
import com.yh.gulimall.order.constant.OrderConstant;
import com.yh.gulimall.order.entity.OrderItemEntity;
import com.yh.gulimall.order.entity.PaymentInfoEntity;
import com.yh.gulimall.order.enume.OrderStatusEnum;
import com.yh.gulimall.order.feign.CartFeignService;
import com.yh.gulimall.order.feign.MemberFeignService;
import com.yh.gulimall.order.feign.ProductFeignService;
import com.yh.gulimall.order.feign.WareFeignService;
import com.yh.gulimall.order.interceptor.LoginUserInterceptor;
import com.yh.gulimall.order.service.OrderItemService;
import com.yh.gulimall.order.service.PaymentInfoService;
import com.yh.gulimall.order.to.OrderCreateTo;
import com.yh.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yh.common.utils.PageUtils;

import com.yh.gulimall.order.dao.OrderDao;
import com.yh.gulimall.order.entity.OrderEntity;
import com.yh.gulimall.order.service.OrderService;
import com.yh.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal=new ThreadLocal<>();

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();//原请求

        CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
            //1、远程查询所有收货地址列表 ->异步任务，要设置老请求内容，否则无法共享数据
            RequestContextHolder.setRequestAttributes(attributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartTask = CompletableFuture.runAsync(() -> {
            //2、远程查询购物车所有选中的购物项 ->异步任务，要设置老请求内容，否则无法共享数据
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItem();
            orderConfirmVo.setItems(cartItems);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //远程调用库存服务查库存
            R skuHasStock = wareFeignService.getSkuHasStock(collect);
            List<SkuHasStockVo> data = skuHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if(data!=null){
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        },executor);


        //3、查询用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        //4、其他数据自动计算

        // TODO 5、防重令牌（幂等性细说）
        String token = UUID.randomUUID().toString().replace("-", "");
        //令牌 服务器一个，页面一个
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressTask,cartTask).get();

        return orderConfirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        //为了之后订单的一系列流程可以用页面提交的数据
        confirmVoThreadLocal.set(orderSubmitVo);
        //获得当前用户
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //下单后的订单返回实体
        SubmitOrderResponseVo orderResponseVo = new SubmitOrderResponseVo();
        //初始化返回码0代表成功
        orderResponseVo.setCode(0);

        //TODO 1、验证令牌->[令牌的比对和删除必须保证原子性的操作] 0令牌失败 - 1删除成功
        String script="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        //这个就是原子性的 比对和删除
        Long result=redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),orderToken);
        if(result==1L){
            //令牌验证成功
            //TODO 2、创建订单，订单项，价格，积分等相关信息
            OrderCreateTo order = orderCreate();
            //TODO 3、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();//计算之后价格
            BigDecimal payPrice = orderSubmitVo.getPayPrice();//页面提交的金额
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){//金额对比成功
                //TODO 4、保存订单
                saveOrder(order);
                //TODO 5、库存锁定 -》有异常 即可回滚订单数据
                //调用远程库存服务  （订单号、所有订单项）-（skuId、skuName，num）
                WareSkuLockVo lockVo=new WareSkuLockVo();
                //订单号
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                //所有订单项
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);
                // TODO 远程锁库存
                //问题一：库存成功，网络原因订单回滚，库存不回滚
                //为了保证高并发。让库存服务自己回滚。可以发消息给库存服务；
                //库存本身可以使用自动解锁模式，消息队列完成这个事
                R r = wareFeignService.orderLockStock(lockVo);
                if(r.getCode()==0){//锁定成功
                    orderResponseVo.setOrder(order.getOrder());

                    // TODO 6、远程扣减积分
//                    int i=10/0;//问题二：订单回滚，库存不回滚
                    // TODO 7、订单创建成功给我们的MQ发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());

                    return orderResponseVo;
                }else{//锁定失败
                    String msg=(String) r.get("msg");
                    throw new NoStockException(msg);
//                    orderResponseVo.setCode(3);
//                    return orderResponseVo;
                }
            }else{//金额比对失败
                orderResponseVo.setCode(2);
                return orderResponseVo;
            }
        }else{
            //临牌验证失败
            orderResponseVo.setCode(1);
            return orderResponseVo;
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关闭订单
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前订单的最新状态
        OrderEntity order = this.getById(orderEntity.getId());
        //关单 ->关闭代付款的订单
        if(order.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            //其实就是改变状态，从代付款-》已关闭
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order,orderTo);

            try {
                //订单关闭成功，主动发送消息给MQ
                //TODO 保证消息一定会发送出去 (每一个消息都可以做好日志记录-》给数据库保存每一个消息的详细信息) 1.已发送2.失败3.成功抵达
                //TODO 定期扫描数据库将失败的消息再次发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                // 消息发送出现问题（网络闪断） TODO 将没法送成功的消息，进行重试发送

            }

        }
    }

    /**
     * 获取订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getPayOrder(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        //订单号
        payVo.setOut_trade_no(order.getOrderSn());
        //订单主题  我们去一个商品当主题即可
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(order_sn.get(0).getSkuName());
        //订单备注
        payVo.setBody(order_sn.get(0).getSkuAttrsVals());
        //订单金额  取两位小数，向上取值
        payVo.setTotal_amount(order.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());

        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        //查询订单下的所有订单项
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    /**
     * 根据支付成功与否来修改订单的状态
     * @param payAsyncVo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        //1、放入交易流水表、方便日后对账
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());//流水号
        infoEntity.setOrderSn(payAsyncVo.getOut_trade_no());//订单号
        infoEntity.setPaymentStatus(payAsyncVo.getTrade_status());//支付状态
        infoEntity.setCallbackTime(payAsyncVo.getNotify_time());//回调时间

        paymentInfoService.save(infoEntity);

        //2、修改订单的状态信息
        if(payAsyncVo.getTrade_status().equals("TRADE_SUCCESS")||payAsyncVo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功
            String outTradeNo = payAsyncVo.getOut_trade_no();//对外交易号
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());

        }

        return "success";
    }

    /**
     * 验价完成之后 -》保存订单、订单项
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrder();
        //插入数据库前设置一些字段
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        //保存订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 订单前三模块 1、生成订单 -》2、获取所有订单数据从购物车 -》3、价格、积分等信息的计算
     * @return
     */
    private OrderCreateTo orderCreate(){
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成一个订单号 mybatis提供的IdWorker
        String orderSn = IdWorker.getTimeId();
        //构建订单
        OrderEntity entity = buildOrder(orderSn);
        createTo.setOrder(entity);

        //2、获取到所有的订单项数据-》注意是从购物车获取。而不是从提交的页面获取
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        createTo.setOrderItems(orderItemEntities);

        //3、验价【计算价格、积分相关信息】
        computePrice(entity,orderItemEntities);

        return createTo;
    }

    /**
     * 1、创建订单信息
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());

        //远程获取收货地址信息+加运费
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo data = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费
        entity.setFreightAmount(data.getFare());
        //设置收货人信息
        entity.setReceiverCity(data.getAddress().getCity());
        entity.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        entity.setReceiverName(data.getAddress().getName());
        entity.setReceiverPhone(data.getAddress().getPhone());
        entity.setReceiverProvince(data.getAddress().getProvince());
        entity.setReceiverPostCode(data.getAddress().getPostCode());
        entity.setReceiverRegion(data.getAddress().getRegion());

        //设置订单的状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);//自动确认收货
        return entity;
    }

    /**
     * 2、构建所有订单项数据
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if(currentUserCartItem!=null&&currentUserCartItem.size()>0){
            List<OrderItemEntity> orderItems = currentUserCartItem.stream().map(cartItem -> {
                //构建订单项
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return orderItems;
        }
        return null;
    }

    /**
     * 2.1、构建每一个订单项
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息：订单号【上一步做完了】
        //2、商品的spu信息  【远程调用商品服务】
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setSpuBrand(data.getBrandId().toString());
        orderItemEntity.setCategoryId(data.getCatalogId());

        //3、商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuPic(cartItem.getImage());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());

        //4、优惠信息【忽略】
        //5、积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额 总额-优惠
        BigDecimal orginPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orginPrice.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount())
                .subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }


    /**
     * 3、计算价格、积分
     * @param entity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity entity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");

        BigDecimal giftIntegration = new BigDecimal("0.0");
        BigDecimal giftGrowth = new BigDecimal("0.0");
        //订单总额=叠加每一个订单项的总额
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            //真实金额
            BigDecimal realAmount = orderItemEntity.getRealAmount();
            total=total.add(realAmount);
            //优惠卷抵扣金额
            BigDecimal couponAmount = orderItemEntity.getCouponAmount();
            coupon=coupon.add(couponAmount);
            //打折抵扣金额
            BigDecimal promotionAmount = orderItemEntity.getPromotionAmount();
            promotion=promotion.add(promotionAmount);
            //积分抵扣金额
            BigDecimal integrationAmount = orderItemEntity.getIntegrationAmount();
            integration=integration.add(integrationAmount);
            //可以获得的积分、和成长值
            giftIntegration.add(new BigDecimal(orderItemEntity.getGiftIntegration()));
            giftGrowth.add(new BigDecimal(orderItemEntity.getGiftGrowth()));
        }
        //1、订单价格相关的
        entity.setTotalAmount(total);//订单总额
        //应付总额【加上运费】
        entity.setPayAmount(total.add(entity.getFreightAmount()));
        //抵扣信息
        entity.setPromotionAmount(promotion);
        entity.setCouponAmount(coupon);
        entity.setIntegrationAmount(integration);
        //可获积分信息
        entity.setGrowth(giftGrowth.intValue());
        entity.setIntegration(giftIntegration.intValue());

        //其他信息
        entity.setDeleteStatus(0);//删除状态默认是0
    }

}